package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

// 通用接口
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {

    @Resource
    private AliOssUtil aliOssUtil;
    @Value("${sky.path.upload-path}")
    private String uploadPath;
    @Value("${sky.path.download-path}")
    private String downloadPath;

    // 文件上传
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) {
        log.info("文件上传：{}", file);

        // 原始文件名
        String originalFilename = file.getOriginalFilename();
        // 截取原始文件名的后缀 xx.png
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 构造新文件名称
        String fileName = UUID.randomUUID().toString() + extension;

//        // 创建一个目录对象   前端限制，转本地失败
//        File dir = new File(uploadPath);
//        // 判断当前目录是否存在
//        if (!dir.exists()) {
//            dir.mkdirs();
//        }
        try {
//            // 将临时文件转存到指定位置
//            file.transferTo(new File(uploadPath + fileName));

            // 文件的请求路径
            String filePath = aliOssUtil.uploadAli(file.getBytes(),fileName);
            return Result.success(filePath);
//            return Result.success(fileName);
        } catch (IOException e) {
            log.error("文件上传失败：{}", e);

        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }

    // 文件下载
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        // 通过输入流读取文件内容
        try {
            FileInputStream fis = new FileInputStream(new File(downloadPath + name));
            // 通过输出流将文件写回浏览器，在浏览器展示图片
            ServletOutputStream os = response.getOutputStream();
            response.setContentType("image/jpeg");

            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = fis.read(bytes)) != -1) {
                os.write(bytes, 0, len);
                os.flush();
            }

            // 关闭资源
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}